<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

jimport( 'joomla.application.component.model' );

/**
 * @package Joomla
 * @subpackage JobBoard
 */
class JobBoardModelJAEmployers extends JModel
{
    var $_data = null;
    var $_table = null;
    var $_pagination;
    var $_fieldListEdit = null;
    var $_table_name = 'ja_profiles';
    
    /**
    * Return the query is used to retrive all row from database
    * @return string The query is used 
    */
    function _buildQuery(){
    	global $mainframe;    	    	
    	
    	$db = &JFactory::getDBO();
    	
    	$filter_location    = $mainframe->getUserStateFromRequest( JBCOMNAME .".jaemployers.filter_location",   'filter_location',        '',    'cmd' );
        $filter_state       = $mainframe->getUserStateFromRequest( JBCOMNAME .".jaemployers.filter_state",      'filter_state',        '',    'word' );
        $filter_catid       = $mainframe->getUserStateFromRequest( JBCOMNAME.".jaemployers.filter_catid",       'filter_catid',        '',    'string' );
        $filter_order		= $mainframe->getUserStateFromRequest( JBCOMNAME .".jaemployers.filter_order",		'filter_order',		'id',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( JBCOMNAME .".jaemployers.filter_order_Dir",	'filter_order_Dir',	'DESC',			'word' );
        $search				= $mainframe->getUserStateFromRequest( JBCOMNAME .".jaemployers.search",			'search',			'',				'string' );
		$search				= JString::strtolower( $search );
		
		$where = array();
		if($filter_location){
            $where[] = "location_id = ". $filter_location;
        }      
          
        if($filter_catid){
        	include_once(dirname(__FILE__).DS.'jacategories.php');
	        $model_cats = new JAJobBoardModelJACategories();
	        $catids[0] = $filter_catid;
	        $catids = $model_cats->getSubcategories($filter_catid, $catids);
	       	$catids = implode(',', $catids);
            $where[] ="cat_id in ($catids)";
        }
		if ($where) $where = 'WHERE '.implode(' and ', $where);
													
    	$query = "SELECT user_id FROM #__ja_profiles $where";    	
        $db->setQuery($query);
        $ids = $db->loadResultArray(0);
        
        if(!$ids) return null;
        $ids = implode(',', $ids);
        
        // just in case filter_order get's messed up
		if ($filter_order) {
			$orderby = ' ORDER BY '.$filter_order .' '. $filter_order_Dir;
		} else {
			$orderby = ' ORDER BY id DESC';
		}
        $orderby = ' ORDER BY id ';
        
        $where = array();
		$where[] = '1=1';
		if($search){
			$where[] = " (name LIKE ". $db->Quote( '%'.$db->getEscaped( $search, true ).'%', false )." or username LIKE ". $db->Quote( '%'.$db->getEscaped( $search, true ).'%', false )." or email LIKE ". $db->Quote( '%'.$db->getEscaped( $search, true ).'%', false ).")";			
		}
		if ( $filter_state == 'P' ) {
				$where[] = 'block=1';
		} else if ($filter_state == 'U' ) {
			 $where[] = 'block=0';
		}		
		
        $where = implode(' and ', $where);
        
        $query = "SELECT * FROM #__users WHERE id in ($ids) and $where $orderby";    	

        return $query;
    }
       
    /**
    * Get field table instance
    * @return JTable Configuration table object
    */
    function _getTable(){
        if($this->_table == null){
        	$this->_table = &JTable::getInstance('JA_Employer', 'JobBoardTable');
        	
        }
		return $this->_table;
	}
	
	/**
	* Get page navigator object
	* @return 
	*/
	function &getPagination(){
		if ($this->_pagination == null) {
			$this->getItems();
		}
		return $this->_pagination;
	}
	
	/**
	* Remove email record
	* @return Number of removed records
	*/
	function remove(){
	    JRequest::checkToken() or jexit( 'Invalid Token' );

		$db 			=& JFactory::getDBO();
		$currentUser 	=& JFactory::getUser();
		$acl			=& JFactory::getACL();
		$cid 			= JRequest::getVar( 'cid', array(), '', 'array' );

		JArrayHelper::toInteger( $cid );

		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( 'Select a User to delete', true ) );
		}

	    
	    if($cid){
		    foreach ($cid as $id)
			{
				// check for a super admin ... can't delete them
				$objectID 	= $acl->get_object_id( 'users', $id, 'ARO' );
				$groups 	= $acl->get_object_groups( $objectID, 'ARO' );
				$this_group = strtolower( $acl->get_group_name( $groups[0], 'ARO' ) );
	
				$success = false;
				if ( $this_group == 'super administrator' )
				{
					$msg = JText::_( 'You cannot delete a Super Administrator' );
				}
				else if ( $id == $currentUser->get( 'id' ) )
				{
					$msg = JText::_( 'You cannot delete Yourself!' );
				}
				else if ( ( $this_group == 'administrator' ) && ( $currentUser->get( 'gid' ) == 24 ) )
				{
					$msg = JText::_( 'WARNDELETE' );
				}
				else
				{
					$user =& JUser::getInstance((int)$id);
					$count = 2;
	
					if ( $user->get( 'gid' ) == 25 )
					{
						// count number of active super admins
						$query = 'SELECT COUNT( id )'
							. ' FROM #__users'
							. ' WHERE gid = 25'
							. ' AND block = 0'
						;
						$db->setQuery( $query );
						$count = $db->loadResult();
					}
	
					if ( $count <= 1 && $user->get( 'gid' ) == 25 )
					{
						// cannot delete Super Admin where it is the only one that exists
						$msg = "You cannot delete this Super Administrator as it is the only active Super Administrator for your site";
					}
					else
					{
						// delete user
						$user->delete();
						$msg = '';
						
						/* Delete employer record*/
						$query = "DELETE FROM #__ja_employers WHERE id = ". implode(" OR id = ", $cid);
				        $db = &JFactory::getDBO();
				        $db->setQuery($query);
				        if($db->query()){
							$row = $this->_getTable();
							$row->reorder();	            
						}
							
						JRequest::setVar( 'task', 'remove' );
						JRequest::setVar( 'cid', $id );
	
						// delete user acounts active sessions
						
					}
				}
			}
			return $msg;
	    }	    
	}

	
	/**
	* Get configuration item
	* @return JobboardTableja_employers Table object
	*/
	
	function getItem($user_id=0){		

		$table = $this->_getTable();
        $table->_tbl_key = 'id';
        $cid = JRequest::getVar('cid');
		if (is_array($cid))
			$cid = $cid[0];
        $table->load($cid);
		
		
	    $item = $table;
	    return $item;	    
	}
		
	/**
	 * Get list Items by condittion
	 *
	 * @return list items
	 */
	function getItems(){
		global $mainframe, $option;

	    $limit				= $mainframe->getUserStateFromRequest( 'global.list.limit',							'limit',			$mainframe->getCfg( 'list_limit' ),	'int' );
		$limitstart			= $mainframe->getUserStateFromRequest( $option. '.jobs.limitstart',		'limitstart',		0,				'int' );
		
		$db = &JFactory::getDBO();
		$query = $this->_buildQuery();
		$db->setQuery($query);	
		$items = $db->loadObjectList();

		$total = count( $items );

		jimport('joomla.html.pagination');
		$this->_pagination = new JPagination( $total, $limitstart, $limit );
		
		$list = array();
		// slice out elements based on limits
		if($items)
		$list = array_slice( $items, $this->_pagination->limitstart, $this->_pagination->limit );
		
		return $list;
	}	
	
	
	/**
    * @desc Get all fields that will be displayed on edit form
    */
    function getEditFieldList(){
        if(!$this->fieldListEdit){	       
	        $this->_fieldListEdit = getEditFieldList($this->_table_name);
        }     
		return $this->_fieldListEdit ; 
        
    }
    
	/**
	 * Get list email by list ids
	 *
	 */
	function getEmails(){
		$cid = JRequest::getVar('cid',array(), 'post', 'array');
	    $n =  count($cid);
	    JArrayHelper::toInteger( $cid );
	    
	    if(!$cid) return '';
	    
	    $cid = implode(',', $cid);
	    
	    $emails = '';
	    
	    $db = &JFactory::getDBO();
	    $query = "select email from #__ja_employers where id in ($cid)";
	    $db->setQuery($query);	
		$emails = $db->loadResultArray(0);
		if ($emails) {
			$emails = implode(',', $emails);
		}
		return $emails;
	}
	
	/** 
	* Store configuration item
	* @param array The post array
	*/
	function store($row=null){
	    // Initialize variables
		$db		=& JFactory::getDBO();
		if(!$row)	$row	=& $this->getItem();
		
		$post	= JRequest::get('request', JREQUEST_ALLOWHTML);
		if (!$row->bind( $post )) {
            echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return false;
		}
		
		
		if (!$row->store())
		{
			echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			
			return false;
		}	
		
		
		return $row->user_id;
	}
	
	function getCurrentProfile()
	{
		$user = JFactory::getUser();
		$db = JFactory::getDBO();
		$query = "SELECT id FROM #__ja_profiles WHERE user_id=".(int)$user->id;
		$db->setQuery($query);
		$profile_id = $db->loadObject();
		require_once JPATH_COMPONENT_SITE.DS.'models'.DS.'japrofiles.php';
		$model_profile = new JobBoardModelJAProfiles();
		JRequest::setVar('cid',$profile_id->id);
		$profile = $model_profile->getItem();
		return $profile;
	}
    
    function save_user($cid)
    {
		$post    = JRequest::get('request', JREQUEST_ALLOWHTML);
		$user = JFactory::getUser($cid);
		$user->name = $post['name'];
		$user->username = $post['username'];
		$user->email = $post['email'];
		$user->sendEmail = $post['sendEmail'];
		
		$user->save();
    	return true;
    }
  
}
?>